
import { useParams } from '@@/exports';
import {PageContainer} from '@ant-design/pro-components';
import {Badge, Button, Card, Descriptions, DescriptionsProps, Divider, message, Modal, Form, Input} from 'antd';
import React, { useEffect, useState } from 'react';
import {
  getQuestionWithAnswerUsingGet
} from "@/services/question-management/questionController";
import {addAnswerUsingPost} from "@/services/question-management/answerController";
import {deleteAnswerUsingPost, updateAnswerUsingPost} from "@/services/backend1/answerController";


const Index: React.FC = () => {
  const [, setLoading] = useState(false);
  const [data, setData] = useState<API.QuestionVO>();
  const params = useParams();
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  const [addModalOpen, handleAddModalOpen] = useState<boolean>(false);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');

  const loadDate = async () => {
    if (!params.id) {
      message.error('参数不存在！');
      return;
    }
    setLoading(true);
    try {
      const res = await getQuestionWithAnswerUsingGet({
        id: Number(params.id),
      });
      setData(res.data);
    } catch (error: any) {
      message.error('加载失败！' + error.message);
    }
    setLoading(false);
  };

  const handlePreview = (url:any) => {
    setPreviewImage(url);
    setPreviewVisible(true);
  };

  const handleClosePreview = () => {
    setPreviewVisible(false);
  };

  const handleAdd = async (values: any) => {
    if (!params.id) {
      message.error('参数不存在！');
      return;
    }
    const hide = message.loading('添加中');
    try {
      await addAnswerUsingPost({
        questionId: params.id,
        ...values,
      });
      hide();
      message.success("添加成功");
      handleAddModalOpen(false);
      loadDate();
    } catch (error: any) {
      message.error('添加失败！'+error.message);
    }
  };

  const handleUpdate = async (values: any) => {
    if (!params.id) {
      message.error('参数不存在！');
      return;
    }
    const hide = message.loading('修改中');
    try {
      await updateAnswerUsingPost({
        questionId: params.id,
        ...values,
      });
      hide();
      message.success("修改成功");
      handleUpdateModalOpen(false);
      loadDate();
    } catch (error: any) {
      message.error('修改失败！'+error.message);
    }
  };

  const handleRemove = async () => {
    const hide = message.loading('正在删除');
    if (!params.id) {
      message.error('参数不存在！');
      return;
    }
    try {
      await deleteAnswerUsingPost({
        id: params.id
      });
      hide();
      message.success('删除成功');
      loadDate();
    } catch (error: any) {
      message.error('删除失败！' + error.message );
    }
  };


  useEffect(() => {
    loadDate();
  }, []);

  const renderButtons = () => {
    if (data?.solution !== null || data?.picture !== null) {
      return (
        <>
          <Button type="primary"  style={{ marginRight: 8 }}
                  onClick={() => {
                    handleUpdateModalOpen(true);
                  }}
          >修改答案</Button>
          <Button type="primary" danger
                  onClick={() => {
                    handleRemove();
                  }}
          >删除答案</Button>
        </>
      );
    } else {
      return (
        <Button type="primary" htmlType="submit"
                onClick={() => {
                  handleAddModalOpen(true);
                }}
        >添加答案
        </Button>
      );
    }
  };
  const items: DescriptionsProps['items'] = [
    {
      key: '1',
      label: '题目编号',
      children: data?.id,
      span: 1,
    },
    {
      key: '6',
      label: '难易度',
      children: <Badge status={data?.difficulty === 0 ? "processing" : data?.difficulty === 1 ? "success" : "error"} text={data?.difficulty === 0 ? "简单" : data?.difficulty === 1 ? "普通" : "困难"} />,
    },
    {
      key: '3',
      label: '错误率',
      children: data?.errorRate,
      span: 1,
    },
    {
      key: '2',
      label: '章节',
      children: data?.chapter,
      span: 2,
    },
    {
      key: '4',
      label: '易错点',
      children: data?.errorProne,
    },
    {
      key: '4',
      label: '题目内容',
      children: data?.questionContent,
      span: 3,
    },
    {
      key: '10',
      label: '贴图',
      children: data?.texture ? <img src={data.texture}  style={{ width: '600px' }} /> : "暂无图片",
      span: 3,
    },
  ];

  const answer: DescriptionsProps['items'] = [
    {
      key: '1',
      label: '文字解析',
      children: data?.solution,
      span: 3,
    },
    {
      key: '2',
      label: '图片解析',
      children: data?.picture ? <img src={data.picture}  style={{ width: '600px' }} onClick={() => handlePreview(data.picture)} /> : "暂无图片",
      span: 3,
    },
  ];

  return (
    <PageContainer title={'查看题目解答'}>
      <Card>
        {data ?<Descriptions title={data?.questionType === "choose" ? "选择题":data?.questionType === "blanking" ? "填空题":"主观题"} bordered items={items}/> : <>题目不存在</>}
      </Card>
      <Divider/>
      <Card title="答案解析">
        {data?.solution !== null || data?.picture !== null ?<Descriptions bordered items={answer}/> : <>答案不存在</>}
        <Divider/>
        {renderButtons()}
      </Card>
      <Modal
        open={previewVisible}
        footer={null}
        onCancel={handleClosePreview}
        style={{ textAlign: 'center' }}
        width={1200}
      >
        <img alt="预览图片" style={{ maxWidth: '100%', maxHeight: '100vh' }} src={previewImage} />
      </Modal>
      <Modal
        title="修改答案"
        open={updateModalOpen}
        onCancel={() => {
          handleUpdateModalOpen(false);

        }}
        footer={null}
      >
        <Form onFinish={handleUpdate} initialValues={{ solution: data?.solution, picture: data?.picture }}>
          <Form.Item label="文字答案" name="solution">
            <Input />
          </Form.Item>
          <Form.Item label="图片答案" name="picture">
            <Input />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="添加答案"
        open={addModalOpen}
        onCancel={() => {
          handleAddModalOpen(false);
        }}
        footer={null}
      >
        <Form onFinish={handleAdd} >
          <Form.Item label="文字答案" name="solution">
            <Input />
          </Form.Item>
          <Form.Item label="图片答案" name="picture">
            <Input />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default Index;
